package chatRoom.server;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 启动服务器,等待客户端连接
 * 读取客户端发送来的信息,并将服务器上的信息发送给所有的客户端
 */
public class ClientHandler implements Runnable{
    private Socket socket;
    private String host;
    private List<PrintWriter>allOut= Collections.synchronizedList(new ArrayList<>());
    public ClientHandler(Socket socket) {
        this.socket=socket;
        host=socket.getInetAddress().getCanonicalHostName();
    }

    @Override
    /**
     * 读取客户端发送过来的聊天信息
     * 将服务器短的信息发送给所有的客户端
     */
    public void run() {
        PrintWriter pw=null;
        try {
            pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8")),true);
            BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
            allOut.add(pw);
            String message;
            System.out.println(host+"上线了,当前在线人数:"+allOut.size());
            while((message=br.readLine())!=null){
                System.out.println(host+":"+message);
                sendMessage(host+":"+message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            allOut.remove(pw);
            System.out.println(host+"下线了,当前在线人数:"+allOut.size());
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public void sendMessage(String message){
        allOut.forEach(pw->pw.println(message));
    }
}
